package com.hx.service.Impl;

import com.hx.mapper.AccountMapper;
import com.hx.pojo.Account;
import com.hx.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public Boolean transfer(String fromAccountNum, String toAccountNum, Integer money) {

        //判断转账方是否存在
        Account fromAccount = accountMapper.findByAccountNum(fromAccountNum);
        if (fromAccount == null) {
            throw new RuntimeException("账户不存在请先开户");
        }
        //判断转账方是否存在 存在继续执行  不存在输入正确的账户
        Account toAccount =accountMapper.findByAccountNum(toAccountNum);
        if (toAccount == null) {
            throw new RuntimeException("账户不存在 请输入正确的账户");
        }
        //转账方余额是否充足  够  继续执行  不够充钱
        if (fromAccount.getBalance()<money) {
           throw new RuntimeException("余额不足");
       }

       //转账方- 金额 成功继续执行  不成功 返回错误
       fromAccount.setBalance(fromAccount.getBalance()-money);
       accountMapper.updateAccountBalance(fromAccount);


       //收款方 +金额  成功 完成   不成功 返回错误
       toAccount.setBalance(toAccount.getBalance() + money);
       accountMapper.updateAccountBalance(toAccount);
        return true;
    }
}
